package com.ran.java_gobang.game;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-08-28
 * Time: 19:57
 */
@Component
public class OnlineUserManager {
    // 这个哈希表来存储当前用户的游戏大厅在线状态
    // 保证多线程状态下 对哈希桶修改不出错误, 分为了多个哈希桶, 每个哈希桶进行了加锁
    private ConcurrentHashMap<Integer, WebSocketSession> gameHall = new ConcurrentHashMap<>();

    // 这个哈希表表示用户在游戏房间内的在线状态
    private ConcurrentHashMap<Integer, WebSocketSession> gameRoom = new ConcurrentHashMap<>();

    // 进入游戏大厅
    public void enterGameHall(int userId, WebSocketSession webSocketSession) {
        gameHall.put(userId,webSocketSession);
    }

    // 离开游戏大厅
    public void exitGameHall(int userId) {
        gameHall.remove(userId);
    }

    // 查找用户的回话session
    public WebSocketSession getFromGameHall(int userId) {
        return gameHall.get(userId);
    }

    public void enterGameRoom(int userId, WebSocketSession webSocketSession) {
        gameRoom.put(userId,webSocketSession);
    }

    public void exitGameRoom(int userId) {
        gameRoom.remove(userId);
    }

    public WebSocketSession getFromGameRoom(int userId) {
        return gameRoom.get(userId);
    }
}
